"""
cron任务
每小时执行一次 0：50， 1：50。。 23:50
统计订单
"""
import logging
from datetime import datetime

from django.core.management.base import BaseCommand
from django.db.models import Avg

from biz.core.thanos.models import WorkOrder, Performance, Report, ProConfig
from biz.const import WorkOrderStatus, ProblemType, Role, Comment, IsSolved
from gis.admin.models import User

_LOGGER = logging.getLogger(__name__)

"""
    将当天的 每种问题类型 每种2级分类，每种3级分类， 聚合一条数据
    二级分类
    question_type
    问题类别  1类充值问题 没有
             2类提现问题 201=提现未到账 202=其他问题
             3类账号问题 301=无法注册 302=异常登录 303=保险柜问题 304=无法接收验证码 305=其他问题
             4类游戏问题 401=掉线 402=闪退 403=自动弃牌 404=结算未派奖 405=点击操作按钮无反应 406=游戏卡住无法退出 407=其他问题
             5类商务合作 没有
             6类其他问题 601=问题 602=建议
    三级分类
    game       游戏 1=捕鱼 2=斗地主 3=龙虎斗 4=水浒传 5=炸金花 6=金鲨银鲨 7=血拼牛牛 8=百人牛牛 9=红黑大战 10=抢庄牛牛
"""

# 其他问题类型
question_type = [201, 202,
                 301, 302, 303, 304, 305,
                 601, 602]
# 游戏问题类型
question_type_game = [401, 402, 403, 404, 405, 406, 407]

# 游戏分类
game_type = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


def calc_report():
    today = datetime.now().strftime('%Y-%m-%d 00:00:00')
    day = datetime.now().strftime('%Y-%m-%d')

    # 分平台聚合
    pros = ProConfig.objects.all()
    for pro in pros:
        # [1类充值问题  5类商务合作]   无二级分类，无三级分类
        for type_id in [ProblemType.RECHARGE, ProblemType.COOPERATION]:
            finish_count = WorkOrder.objects.filter(pro_id=pro.id).filter(created_at__gte=today).filter(
                status=WorkOrderStatus.FINISHED).filter(type_id=type_id).count()
            wait_count = WorkOrder.objects.filter(pro_id=pro.id).filter(created_at__gte=today).filter(
                status=WorkOrderStatus.WAITING).filter(type_id=type_id).count()
            total_count = finish_count + wait_count
            solved_count = WorkOrder.objects.filter(pro_id=pro.id).filter(created_at__gte=today).filter(
                status=WorkOrderStatus.FINISHED).filter(is_solved=IsSolved.SOLVED).filter(type_id=type_id).count()
            unsolved_count = WorkOrder.objects.filter(pro_id=pro.id).filter(created_at__gte=today).filter(
                status=WorkOrderStatus.FINISHED).filter(is_solved=IsSolved.UNSOLVED).filter(type_id=type_id).count()

            report = Report.objects.filter(pro_id=pro.id).filter(day=day).filter(type_id=type_id).first()
            if report:
                report.finish_count = finish_count
                report.wait_count = wait_count
                report.total_count = total_count
                report.solved_count = solved_count
                report.unsolved_count = unsolved_count
            else:
                Report.objects.create(pro_id=pro.id, day=day, type_id=type_id, finish_count=finish_count,
                                      wait_count=wait_count, total_count=total_count, solved_count=solved_count,
                                      unsolved_count=unsolved_count)

        # [2类提现问题  3类账号问题  6类其他问题]   无三级分类
        for type_id in [ProblemType.WITHDRAW, ProblemType.ACCOUNT, ProblemType.OTHER]:
            for second_type in question_type:
                finish_count = WorkOrder.objects.filter(pro_id=pro.id).filter(created_at__gte=today).filter(
                    status=WorkOrderStatus.FINISHED).filter(type_id=type_id).filter(question_type=second_type).count()
                wait_count = WorkOrder.objects.filter(created_at__gte=today).filter(
                    status=WorkOrderStatus.WAITING).filter(type_id=type_id).filter(question_type=second_type).count()
                total_count = finish_count + wait_count
                if total_count == 0:
                    continue
                solved_count = WorkOrder.objects.filter(pro_id=pro.id).filter(created_at__gte=today).filter(
                    status=WorkOrderStatus.FINISHED).filter(is_solved=IsSolved.SOLVED).filter(type_id=type_id).filter(
                    question_type=second_type).count()
                unsolved_count = WorkOrder.objects.filter(pro_id=pro.id).filter(created_at__gte=today).filter(
                    status=WorkOrderStatus.FINISHED).filter(is_solved=IsSolved.UNSOLVED).filter(type_id=type_id).filter(
                    question_type=second_type).count()
                report = Report.objects.filter(pro_id=pro.id).filter(day=day).filter(type_id=type_id).filter(
                    second_type=second_type).first()
                if report:
                    report.finish_count = finish_count
                    report.wait_count = wait_count
                    report.total_count = total_count
                    report.solved_count = solved_count
                    report.unsolved_count = unsolved_count
                else:
                    Report.objects.create(pro_id=pro.id, day=day, type_id=type_id, second_type=second_type,
                                          finish_count=finish_count, wait_count=wait_count, total_count=total_count,
                                          solved_count=solved_count, unsolved_count=unsolved_count)

        # [4类游戏问题]
        for second_type in question_type_game:
            for game in game_type:
                finish_count = WorkOrder.objects.filter(pro_id=pro.id).filter(created_at__gte=today).filter(
                    status=WorkOrderStatus.FINISHED).filter(type_id=ProblemType.GAME).filter(
                    question_type=second_type).filter(game=game).count()
                wait_count = WorkOrder.objects.filter(pro_id=pro.id).filter(created_at__gte=today).filter(
                    status=WorkOrderStatus.WAITING).filter(type_id=ProblemType.GAME).filter(
                    question_type=second_type).filter(game=game).count()
                total_count = finish_count + wait_count
                if total_count == 0:
                    continue
                solved_count = WorkOrder.objects.filter(pro_id=pro.id).filter(created_at__gte=today).filter(
                    status=WorkOrderStatus.FINISHED).filter(is_solved=IsSolved.SOLVED).filter(
                    type_id=ProblemType.GAME).filter(
                    question_type=second_type).filter(game=game).count()
                unsolved_count = WorkOrder.objects.filter(pro_id=pro.id).filter(created_at__gte=today).filter(
                    status=WorkOrderStatus.FINISHED).filter(is_solved=IsSolved.UNSOLVED).filter(
                    type_id=ProblemType.GAME).filter(question_type=second_type).filter(game=game).count()
                report = Report.objects.filter(pro_id=pro.id).filter(day=day).filter(type_id=ProblemType.GAME).filter(
                    second_type=second_type).filter(third_type=game).first()
                if report:
                    report.finish_count = finish_count
                    report.wait_count = wait_count
                    report.total_count = total_count
                    report.solved_count = solved_count
                    report.unsolved_count = unsolved_count
                else:
                    Report.objects.create(pro_id=pro.id, day=day, type_id=type_id, second_type=second_type,
                                          third_type=game, finish_count=finish_count, wait_count=wait_count,
                                          total_count=total_count, solved_count=solved_count,
                                          unsolved_count=unsolved_count)


"""
    将当天的 每个客服 每种问题类型 聚合一条数据
"""


def calc_performance():
    today = datetime.now().strftime('%Y-%m-%d 00:00:00')
    day = datetime.now().strftime('%Y-%m-%d')
    # 取到所有客服
    users = User.objects.filter(deleted=False).filter(role_id=Role.KEFU).all()
    for user in users:
        for type_id in [ProblemType.WITHDRAW, ProblemType.ACCOUNT, ProblemType.GAME, ProblemType.COOPERATION,
                        ProblemType.OTHER]:
            # 已处理/待处理/好评数/差评数/好评率/平均处理时长
            finish_count = WorkOrder.objects.filter(created_at__gte=today).filter(handler_id=user.id).filter(
                status=WorkOrderStatus.FINISHED).filter(type_id=type_id).count()
            wait_count = WorkOrder.objects.filter(created_at__gte=today).filter(handler_id=user.id).filter(
                status=WorkOrderStatus.WAITING).filter(type_id=type_id).count()
            if finish_count + wait_count == 0:
                continue
            comment_good_count = WorkOrder.objects.filter(created_at__gte=today).filter(handler_id=user.id).filter(
                status=WorkOrderStatus.FINISHED).filter(comment=Comment.GOOD).filter(type_id=type_id).count()
            comment_bad_count = WorkOrder.objects.filter(created_at__gte=today).filter(handler_id=user.id).filter(
                status=WorkOrderStatus.FINISHED).filter(comment=Comment.BAD).filter(type_id=type_id).count()
            good_percent = (comment_good_count / (
                    comment_good_count + comment_bad_count)) if comment_good_count + comment_bad_count > 0 else 0
            avg_data = WorkOrder.objects.filter(created_at__gte=today).filter(handler_id=user.id).filter(
                status=WorkOrderStatus.FINISHED).filter(type_id=type_id).aggregate(Avg('process_time'))
            avg_process_time = avg_data.get('process_time__avg') if avg_data.get('process_time__avg') else 0

            performance = Performance.objects.filter(user_id=user.id).filter(day=day).filter(type_id=type_id).first()
            if performance:
                performance.finish_count = finish_count
                performance.wait_count = wait_count
                performance.comment_good_count = comment_good_count
                performance.comment_bad_count = comment_bad_count
                performance.good_percent = good_percent
                performance.avg_process_time = avg_process_time
            else:
                Performance.objects.create(user_id=user.id, day=day, type_id=type_id, finish_count=finish_count,
                                           wait_count=wait_count, comment_good_count=comment_good_count,
                                           comment_bad_count=comment_bad_count, good_percent=good_percent,
                                           avg_process_time=avg_process_time)
    # 取到所有支付运营
    users = User.objects.filter(deleted=False).filter(role_id=Role.CHARGE_YUNYIN).all()
    for user in users:
        # 已处理/待处理/好评数/差评数/好评率/平均处理时长
        finish_count = WorkOrder.objects.filter(created_at__gte=today).filter(handler_id=user.id).filter(
            status=WorkOrderStatus.FINISHED).filter(type_id=ProblemType.RECHARGE).count()
        if finish_count == 0:
            continue
        comment_good_count = WorkOrder.objects.filter(created_at__gte=today).filter(handler_id=user.id).filter(
            status=WorkOrderStatus.FINISHED).filter(comment=Comment.GOOD).filter(type_id=ProblemType.RECHARGE).count()
        comment_bad_count = WorkOrder.objects.filter(created_at__gte=today).filter(handler_id=user.id).filter(
            status=WorkOrderStatus.FINISHED).filter(comment=Comment.BAD).filter(type_id=ProblemType.RECHARGE).count()
        good_percent = (comment_good_count / (
                comment_good_count + comment_bad_count)) if comment_good_count + comment_bad_count > 0 else 0
        avg_data = WorkOrder.objects.filter(created_at__gte=today).filter(handler_id=user.id).filter(
            status=WorkOrderStatus.FINISHED).filter(type_id=ProblemType.RECHARGE).aggregate(Avg('process_time'))
        avg_process_time = avg_data.get('process_time__avg') if avg_data.get('process_time__avg') else 0

        performance = Performance.objects.filter(user_id=user.id).filter(day=day).filter(
            type_id=ProblemType.RECHARGE).first()
        if performance:
            performance.finish_count = finish_count
            performance.comment_good_count = comment_good_count
            performance.comment_bad_count = comment_bad_count
            performance.good_percent = good_percent
            performance.avg_process_time = avg_process_time
        else:
            Performance.objects.create(user_id=user.id, day=day, type_id=ProblemType.RECHARGE,
                                       finish_count=finish_count, comment_good_count=comment_good_count,
                                       comment_bad_count=comment_bad_count, good_percent=good_percent,
                                       avg_process_time=avg_process_time)


def start():
    calc_report()
    calc_performance()


class Command(BaseCommand):

    def handle(self, **kwargs):
        start()
